// n = 9, max = 34, array = [6, 6, 6, 8, 8, 8, 5, 5, 1]
//n = 9, max = 37, array = [9, 9, 9, 9, 6, 6, 6, 6, 13]
// n = 9, max = 40, array = [1, 11, 13, 12, 7, 8, 11, 5, 6]
//n = 6, max = 50, array = [13, 13, 13, 1, 1, 1]
//n = 31, max = 42, array = [3, 3, 11, 12, 12, 2, 13, 5, 13, 1, 13, 8, 8, 1, 8, 13, 12, 9, 2, 11, 3, 5, 8, 11, 1, 11, 1, 5, 4, 2, 5]
n = 9, max = 34, array = [6, 6, 6, 8, 8, 8, 5, 5, 1]


// function solution(n, max, array) {
//     let Hash = {};
//     for (let i = 0; i < n; i++) {
//         if (!Hash[array[i]]) {
//             Hash[array[i]] = 0;
//         }
//         Hash[array[i]]++;
//     }

//     let two = [];
//     let three = [];
//     for (let key in Hash) {
//         let count = Hash[key];
//         key = parseInt(key); // 转换为整数
//         if (count >= 2) {
//             two.push(key);
//         }
//         if (count >= 3) {
//             three.push(key);
//         }
//     }

//     if (three.length === 0) return [0, 0]; // 无法组成葫芦

//     let hulu = [0, 0];
//     let huluMax = 0;

//     // 检查三张牌和两张牌组合
//     for (let i = 0; i < three.length; i++) {
//         for (let j = 0; j < two.length; j++) {
//             let a = three[i];
//             let b = two[j];
//             let sum = a * 3 + b * 2;
//             if (sum <= max && (sum > huluMax || (sum === huluMax && (a > hulu[0] || (a === hulu[0] && b > hulu[1]))))) {
//                 hulu = [a, b];
//                 huluMax = sum;
//             }
//         }
//     }

//     // 检查三张牌和三张牌组合
//     for (let i = 0; i < three.length; i++) {
//         for (let j = 0; j < three.length; j++) {
//             if (i !== j) {
//                 let a = three[i];
//                 let b = three[j];
//                 let sum = a * 3 + b * 2;
//                 if (sum <= max && (sum > huluMax || (sum === huluMax && (a > hulu[0] || (a === hulu[0] && b > hulu[1]))))) {
//                     hulu = [a, b];
//                     huluMax = sum;
//                 }
//             }
//         }
//     }

//     return hulu;
// }

function solution(n, max, array) {
    if (n !== array.length) {
        throw new Error("The length of the array does not match n");
    }

    // 统计每张牌的出现次数
    const count = {};
    array.forEach(num => {
        count[num] = (count[num] || 0) + 1;
    });

    // 牌值从大到小的优先级列表
    const vals = [1, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2];

    // 遍历所有可能的 x 和 y
    for (let x of vals) {
        for (let y of vals) {
            if (
                x * 3 + y * 2 <= max && // 检查总和是否符合限制
                (count[x] || 0) >= 3 && // 检查 x 是否至少出现 3 次
                (count[y] || 0) >= 2 && // 检查 y 是否至少出现 2 次
                x !== y // x 和 y 必须不同
            ) {
                return [x, y];
            }
        }
    }

    return [0, 0]; // 无法组成符合条件的葫芦
}


console.log(solution(n, max, array));
